//
//  CWQ_locationTool.m
//  sanda
//
//  Created by 陈武琦 on 16/9/22.
//  Copyright © 2016年 陈武琦. All rights reserved.
//
#import "CWQ_locationTool.h"
//引入定位功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import "AFHTTPSessionManager.h"

//是否开启定位服务
#define cwq_locationServicesEnabled [CLLocationManager locationServicesEnabled]

//是否有定位权限
#define cwq_authorizationStatus     ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)




@interface CWQ_locationTool()<BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,UIAlertViewDelegate>
@property(nonatomic, strong)BMKLocationService *locService;
@property(nonatomic, strong)BMKGeoCodeSearch* geocodesearch;
@property(nonatomic, strong)UIAlertView* alertV;
@property(nonatomic, strong)BMKUserLocation *location;
@property(nonatomic,copy)void (^success)(NSString *address,double latitude, double longitude);
@property(nonatomic,copy)void (^failure)(NSString *);
@end



@implementation CWQ_locationTool

+ (instancetype)manager
{
    static CWQ_locationTool *manager = nil;
    //block
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CWQ_locationTool alloc] init];
    });
    return manager;
}

- (void)locationSuccess:(void (^)(NSString *address,double latitude, double longitude))success failure:(void (^)(NSString *reason))failure {

    _success = success;
    _failure = failure;

    [self startLocation];
    //增加监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appHasGoneInForeground)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
}


#pragma mark - 懒加载
- (BMKLocationService *)locService {
    if (!_locService) {
        //初始化BMKLocationService
        _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
        
    }
    return _locService;
}


- (UIAlertView *)alertV {
    if (!_alertV) {
        _alertV = [[UIAlertView alloc] initWithTitle:@"打开定位开关" message:@"定位服务未开启，请进入系统【设置】>【隐私】>【定位服务】中打开开关，并允许护礼家云课堂使用定位服务" delegate:self
                                   cancelButtonTitle:@"取消" otherButtonTitles:@"去开启", nil];
    }
    
    return _alertV;
}

- (BMKGeoCodeSearch *)geocodesearch {
    if (!_geocodesearch) {
        _geocodesearch = [[BMKGeoCodeSearch alloc]init];
        _geocodesearch.delegate = self;
    }
    return _geocodesearch;
}

#pragma mark - ------------------创建内容----------------------------
- (void)startLocation {
    
    if (cwq_locationServicesEnabled && cwq_authorizationStatus) {
        //启动LocationService
        [self.locService startUserLocationService];
       // cwqHud([[UIApplication sharedApplication] keyWindow]);
    }else {
        [self.alertV show];
    }
}

#pragma mark - -------------程序进入前台-----------------
- (void)appHasGoneInForeground {
    [self startLocation];
}
- (void)dealloc {
    //别忘了删除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



#pragma mark - -------------BMKLocationServiceDelegate----------------
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _location = userLocation;
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude};
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [self.geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if (!flag) {
        if (_failure) {
            self.failure(@"解析失败");
        }
       // alertMessage(@"定位失败,请稍后重试");
    }
    [_locService stopUserLocationService];
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
    //alertMessage(@"定位失败,请稍后重试");
    if (self.failure) {
        self.failure(@"定位失败");
        
    }
}


#pragma mark - -------------BMKGeoCodeSearchDelegate----------------
//坐标转换为具体地址
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@"%@",result);
    if (self.success) {
        
        self.success(result.address, self.location.location.coordinate.latitude, self.location.location.coordinate.longitude);
    }
   // cwqHudHidden;
}




#pragma mark--------UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 1) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        
    }
}


@end



